/**
 * Created by xuchaosheng on 16/9/14.
 */
services.factory('chartServ', ["$rootScope", "tools", "$timeout", "$routeParams", function ($rootScope, tools, $timeout, $routeParams) {
    return {
        chartTips: {
            bubble: '建议您使用一个维度,两个度量以及一个表示气泡大小的度量(右键可以分类查看数据)',
            provinceMap: '建议您使用一个表示省份(如浙江省或浙江)的维度以及一个度量',
            verBar: '建议您使用一或多个维度以及一或多个度量(右键可以分类查看数据)',
            cityMap: '建议您使用一个表示城市(如杭州市或杭州)的维度以及一个度量',
            heatmap: '建议您使用一个经度一个纬度以及一个度量',
            heatmarketmap:'建议您使用一个经度一个纬度',
            line: '建议您使用一或多个维度以及一或多个度量(右键可以分类查看数据)',
            bar: '建议您使用一或多个维度以及一或多个度量(右键可以分类查看数据)',
            treemap: '建议您使用一或多个维度以及一个度量',
            nestedPie: '建议您使用两个维度以及一个度量',
            scatter: '建议您使用一个维度以及两个度量',
            pie: '建议您使用一或多个维度以及一个度量',
            circularPie: '建议您使用一或多个维度以及一个度量',
            radar: '建议您使用一个维度以及多个度量',
            histogram: '建议您使用一个度量以及一个维度',
            funnel: '建议您使用多个度量',
            dashboard: '暂无提示',
            waterfall: '暂无提示'
        },
        chartAvailable: function (config) {
            // 饼图,一或多个维度,一个度量
            if (config.chartType == 'pie') {
                return config.dimension.length >= 1 && config.measure.length == 1;
            }
            // 饼图,一或多个维度,一个度量
            if (config.chartType == 'circularPie') {
                return config.dimension.length >= 1 && config.measure.length == 1;
            }
            // 嵌套饼图,两个维度,一个度量
            if (config.chartType == 'nestedPie') {
                return config.dimension.length == 2 && config.measure.length == 1;
            }
            // 折线图,一或多个维度,一或多个度量
            if (config.chartType == 'line') {
                return config.dimension.length >= 1 && config.measure.length >= 1;
            }
            if (config.chartType == 'bar' || config.chartType == 'verBar') {
                return config.dimension.length >= 1 && config.measure.length >= 1;
            }
            if (config.chartType == 'waterfall') {
                return true;
            }
            if (config.chartType == 'area') {
                return config.dimension.length >= 1 && config.measure.length >= 1;
            }
            if (config.chartType == 'bubble') {
                return config.dimension.length === 1 && config.measure.length === 2 && config.measure2.length === 1;
            }
            if (config.chartType == 'scatter') {
                return config.dimension.length == 1 && config.measure.length === 2;
            }
            if (config.chartType == 'radar') {
                return config.dimension.length == 1 && config.measure.length >= 1;
            }
            if (config.chartType == 'funnel') {
                return config.dimension.length === 0 && config.measure.length >= 1;
            }
            if (config.chartType == 'histogram') {
                return config.dimension.length === 1 && config.measure.length === 1 && config.distance;
            }
            if (config.chartType == 'treemap') {
                return config.dimension.length >= 1 && config.measure.length == 1;
            }
            if (config.chartType == 'dashboard') {
                return true;
            }
            if (config.chartType == 'provinceMap') {
                return config.dimension.length === 1 && config.measure.length === 1;
            }
            if (config.chartType == 'cityMap') {
                return config.dimension.length === 1 && config.measure.length === 1;
            }
            if (config.chartType == 'heatmap') {
                return config.dimension.length === 1 && config.dimension2.length === 1 && config.measure.length === 1;
            }
            if (config.chartType == 'heatmarketmap') {
                return config.dimension.length === 1 && config.dimension2.length === 1;
            }
        },
        deleteIbmModuleChartByModuleId: function (config, cb) {
            if (!config) {
                return;
            }
            if (!config.moduleId && config.tmpId) {
                return $rootScope.delChart(config.tmpId);
            }
            tools.get({
                url: '/Ibm-Client/deleteIbmModuleChartByModuleId.htm',
                data: {
                    moduleId: config.moduleId,
                    pageId: $routeParams.id
                },
                succ: function (resp) {
                    if (resp.success) {
                        cb && cb(resp);
                        $rootScope.delChart(config.tmpId || config.moduleId);
                        $rootScope.$broadcast('FIELD_RECOVER_FROM_CHART_EV', [], [],[],[],[], config.chartType,'');
                        $rootScope.$broadcast('CONTEXTMENU_OFF_EV');
                        $rootScope.$broadcast('CONFIRM_OFF_EV');
                    }
                }
            });
        },
        cleanData: function (datas) {
            angular.forEach(datas, function (data) {
                var yKey = [];
                var yVal = [];
                var xKey = [];
                var xVal = [];

                for (var i in data) {
                    if (i.indexOf('group_') != -1) {
                        xKey.push(i);
                        xVal.push(data[i]);
                    }
                }

                data[xKey.join('/')] = xVal.join('/');
            });
        },
        countAxisDistance: function ($container, data) {
            var info = this.countMaxPositiveAndMaxNegativeValue(data);
            var originHeight = this.countMaxLength(data) / 1.414 + 25;

            if (info.maxNegativeValue) {
                return (Math.abs(info.maxNegativeValue) / (info.maxPositiveValue + Math.abs(info.maxNegativeValue))) * ($container.height() - originHeight - 30) + 30;
            } else {
                if ($container.width() / this.collectDimensionFieldKinds(data) > 80) {
                    return 40;
                } else {
                    return this.countMaxLength(data) / 1.414 + 30;
                }
            }
        },
        hasSecondY: function (config) {
            for (var i = 0; i < config.measure.length; i++) {
                if (config.measure[i].setAsSecondY) {
                    return true;
                }
            }
            return false;
        },
        hasMeanLine: function(config){
            if(config.setAsMeanLine){
                return true;
            }
            return false;
        },
        collectSecondYNames: function (config) {
            var res = [];
            for (var i = 0; i < config.measure.length; i++) {
                if (config.measure[i].setAsSecondY) {
                    res.push(config.measure[i].meaType + "_" + config.measure[i].fieldName);
                }
            }
            return res;
        },
        translateMeasureFields: function (data, config) {  // 将所有的度量字段翻译一遍
            var self = this;
            var names = [];

            angular.forEach(data, function (d) {
                for (var i in d) {
                    if (self.isMeasure(i, config)) {
                        var tname = self.translateMeaFieldName(i, config);
                        d[tname] = d[i];
                        if (names.indexOf(tname) == -1) {
                            names.push(tname);
                        }
                    }
                }
            });

            return names;
        },
        translateDimensionFields: function (data, config) { // 将所有的维度字段翻译一遍
            var self = this;
            var names = [];

            angular.forEach(data, function (d) {
                for (var i in d) {
                    if (self.isDimension(i, config)) {
                        var tname = self.translateDimFieldName(i, config);
                        d[tname] = d[i];
                        if (names.indexOf(tname) == -1) {
                            names.push(tname);
                        }
                    }
                }
            });

            return names;
        },
        mergeDimFieldNames: function (datas, config) {
            var self = this;
            angular.forEach(datas, function (data) {
                var dimVal = [];
                for (var i in data) {
                    if (self.isDimension(i, config)) {
                        dimVal.push(angular.copy(data[i]));
                    }
                }
                data['dimension'] = dimVal.join(',');

            });
        },
        // 地图数据对象整理
        mergeMapFieldNames: function (datas, config) {
            var self = this;

            angular.forEach(datas, function (data,index,array) {

                var lngVal,latVal,count;
                for (var i in data) {
                    if (self.isLng(i, config)) {
                        lngVal = data[i];
                    } else if(self.isLat(i,config)){
                        latVal = data[i];
                    } else if(self.isMeasure(i,config)){
                        count = data[i];
                    }
                }

                // console.log(data)
                //array[index] = {lng:lngVal,lat:latVal,count:count};
                data['lng'] = lngVal;
                data['lat'] = latVal;
                data['count'] = count;
            });
  
        },

        // 将多个度量的对象拆分成多个对象
        splitMeaFields: function (datas, config) {
            var self = this, len = datas.length;

            for (var i = 0; i < len; i++) {
                for (var k in datas[i]) {
                    if (self.isMeasure(k, config) && !self.isSecondY(k, config)) {
                        (function () {
                            datas[i].name = self.translateMeaFieldName(k, config);
                            datas[i].measure = datas[i][k];
                            datas.push(angular.copy(datas[i]));
                        })();
                    }
                }
            }

            datas.splice(0, len);

            // 整理分类字段
            for (var j = 0; j < len; j++) {
                for (var k in datas[j]) {
                    if (self.isClassField(k, config)) {
                        datas[j].classification = datas[j][k];
                    }
                }
            }

            // // 整理双Y轴字段
            for (var i = 0; i < datas.length; i++) {
                for (var k in datas[i]) {
                    if (self.isSecondY(k, config)) {
                        datas[i]['secondY' + k] = datas[i][k];
                    }
                }
            }

        },
        // 检测是否是分类字段
        isClassField: function (name, config) {
            if (!config || config.classifies.length === 0) {
                return false;
            }

            for (var i = 0; i < config.classifies.length; i++) {
                if (name.indexOf(config.classifies[i].fieldName) != -1) {
                    return true;
                }
            }

            return false;
        },
        // 检测是否是维度字段
        isDimension: function (name, config) {
            if (!config || config.dimension.length === 0) {
                return false;
            }

            for (var i = 0; i < config.dimension.length; i++) {
                if (name.indexOf(config.dimension[i].fieldName) != -1) {
                    return true;
                }
            }

            if(config.dimension2 && config.dimension2.length){
                for (var i = 0; i < config.dimension2.length; i++) {
                    if (name.indexOf(config.dimension2[i].fieldName) != -1) {
                        return true;
                    }
                }
            }
            return false;
        },
        // 检测是否是经度字段
        isLng: function (name, config) {
            if (!config || config.dimension.length === 0) {
                return false;
            }

            for (var i = 0; i < config.dimension.length; i++) {
                if (name.indexOf(config.dimension[i].fieldName) != -1) {
                    return true;
                }
            }
            return false;
        },
        // 检测是否是纬度字段
        isLat: function (name, config) {
            if (!config || !config.dimension2 || config.dimension2.length === 0) {
                return false;
            }

            if(config.dimension2 && config.dimension2.length){
                for (var i = 0; i < config.dimension2.length; i++) {
                    if (name.indexOf(config.dimension2[i].fieldName) != -1) {
                        return true;
                    }
                }
            }
            return false;
        },
       
        // 检测是否是度量字段
        isMeasure: function (name, config) {
            if (!config || config.measure.length === 0) {
                return false;
            }

            for (var i = 0; i < config.measure.length; i++) {
                if (name.indexOf(config.measure[i].fieldName) != -1) {
                    return true;
                }
            }

            if (config.measure2 && config.measure2.length) {
                for (var i = 0; i < config.measure2.length; i++) {
                    if (name.indexOf(config.measure2[i].fieldName) != -1) {
                        return true;
                    }
                }
            }

            return false;
        },
        isSecondY: function (name, config) {
            for (var i = 0; i < config.measure.length; i++) {
                if (name.indexOf(config.measure[i].fieldName) != -1) {
                    return config.measure[i].setAsSecondY;
                }
            }

            return false;
        },
        // 翻译度量的名字
        translateMeaFieldName: function (fieldName, config) {
            for (var i = 0; i < config.measure.length; i++) {
                if (fieldName.split('_')[1] == config.measure[i].fieldName) {
                    return config.measure[i].columnDesc;
                }
            }

            for (var i = 0; i < config.measure2.length; i++) {
                if (fieldName.split('_')[1] == config.measure2[i].fieldName) {
                    return config.measure2[i].columnDesc;
                }
            }

            return fieldName;
        },
        // 翻译维度的名字
        translateDimFieldName: function (fieldName, config) {
            for (var i = 0; i < config.dimension.length; i++) {
                if (fieldName.split('_')[1] == config.dimension[i].fieldName) {
                    return config.dimension[i].columnDesc;
                }
            }

            for (var i = 0; i < config.dimension2.length; i++) {
                if (fieldName.split('_')[1] == config.dimension2[i].fieldName) {
                    return config.dimension2[i].columnDesc;
                }
            }

            return fieldName;
        },
        collectMeasureFieldNames: function (config) {
            var res = [];
            for (var i = 0; i < config.measure.length; i++) {
                res.push(config.measure[i].meaType + '_' + config.measure[i].fieldName);
            }

            return res;
        },
        collectMeausreTranslatedFieldNames: function (config) {
            var res = [];
            for (var i = 0; i < config.measure.length; i++) {
                res.push(config.measure[i].columnDesc);
            }

            return res;
        },
        collectDimensionFieldNames: function (config) {
            var res = [];
            for (var i = 0; i < config.dimension.length; i++) {
                res.push(config.dimension[i].meaType + '_' + config.dimension[i].fieldName);
            }
            return res;
        },
        collectDimensionColumnIds: function (config) {
            var res = [];
            for (var i = 0; i < config.dimension.length; i++) {
                res.push(config.dimension[i].columnId);
            }
            return res;
        },
        collectMeasurementColumnIds: function () {
            var res = [];
            for (var i = 0; i < config.measure.length; i++) {
                res.push(config.measure[i].columnId);
            }
            return res;
        },
        collectDimensionFieldKinds: function (data) {
            var res = [];
            angular.forEach(data, function (d) {
                if (res.indexOf(d.dimension) == -1) {
                    res.push(d.dimension);
                }
            });
            return res.length;
        },
        makeTitleForChart: function (config) {
            var dimensionColumnDesc = [], measureColumnDesc = [];
            angular.forEach(config.dimension, function (dim) {
                dimensionColumnDesc.push(dim.columnDesc);
            });
            angular.forEach(config.measure, function (mea) {
                measureColumnDesc.push(mea.columnDesc);
            });
            if (dimensionColumnDesc.length && measureColumnDesc.length) {
                config.ctitle = dimensionColumnDesc.join(',') + '-' + measureColumnDesc.join(',');
            } else if (dimensionColumnDesc.length && !measureColumnDesc.length) {
                config.ctitle = dimensionColumnDesc.join(',');
            } else {
                config.ctitle = measureColumnDesc.join(',');
            }
        },
        random: function (data) {
            angular.forEach(data, function (d) {
                for (var i in d) {
                    if (i.indexOf('sum_') != -1) {
                        d[i] = Math.random() * 100;
                    }
                }
            });
        },
        countMaxLength: function (data) {
            if ($('#countMaxLength').size() == 0) {
                $('body').append($("<span id = 'countMaxLength' style='visibility: hidden;'></span>"));
            }

            var $ele = $('#countMaxLength');
            var ml = 50;
            for (var i = 0; i < data.length; i++) {
                $ele.html(data[i].dimension);
                if ($ele.width() > ml) {
                    ml = $ele.width();
                }
            }
            $ele.html('');
            return ml;
        },
        countMaxLegendLength: function (config, data) {
            if ($('#countMaxLength').size() == 0) {
                $('body').append($("<span id = 'countMaxLength' style='visibility: hidden;'></span>"));
            }

            var $ele = $('#countMaxLength');
            var ml = 50;

            if (config.classifies.length) {
                for (var i = 0; i < data.length; i++) {
                    $ele.html(data[i].classification);
                    if ($ele.width() > ml) {
                        ml = $ele.width();
                    }
                }
            } else {
                for (var i = 0; i < data.length; i++) {
                    $ele.html(data[i].name);
                    if ($ele.width() > ml) {
                        ml = $ele.width();
                    }
                }
            }

            $ele.html('');
            return ml;
        },
        drawAllCharts: function (chartType, datas, config, $ele, chartIdent) {

            var res = this[chartType](datas, config, $ele, chartIdent);
            // if (res) {
            //     if (tools.mobileEnv()) {
            //         alert('绘画有结果');
            //     }
            // } else {
            //     if (tools.mobileEnv()) {
            //         alert('绘画没有结果');
            //     }
            // }
            return res;
        },
        countMaxPositiveAndMaxNegativeValue: function (datas) {
            var maxPositiveValue = 0;
            var maxNegativeValue = 0;

            for (var i = 0; i < datas.length; i++) {
                if (datas[i].measure > 0 && datas[i].measure > maxPositiveValue) {
                    maxPositiveValue = datas[i].measure;
                }
                if (datas[i].measure < 0 && datas[i].measure < maxNegativeValue) {
                    maxNegativeValue = datas[i].measure;
                }
            }

            return {
                maxPositiveValue: maxPositiveValue,
                maxNegativeValue: maxNegativeValue
            };
        },
        pie: function (data, config, $container, chartIdent) {
            this.mergeDimFieldNames(data, config);
            this.splitMeaFields(data, config);

            if (!config.filters.sortField) {
                data.sort(function (d1, d2) {
                    return d2.measure - d1.measure;
                });
            }

            var Stat = G2.Stat, chart = new G2.Chart({
                id: chartIdent,
                width: $container.width(),
                height: $container.height(),
                plotCfg: {
                    margin: [55, 120, 20, 20]
                }
            });
            chart.source(data);
            chart.coord('theta', {
                radius: 0.8
            });
            // chart.legend(false);
            chart.legend('dimension',{
                position:'right',
                title: null
            });
            chart.intervalStack().position(Stat.summary.percent('measure')).color('dimension', G2.Global.colors['default']).label('dimension*..percent', function (name, percent) {
                percent = (percent * 100).toFixed(2) + '%';
                return name + ' ' + percent;
            });

            // 下钻
            chart.on('plotclick', function (ev) {
                if (!config.isDrill || config.filters.layerNum == config.dimension.length - 1) {
                    return;
                }
                if (!ev.data) {
                    return;
                }
                config.downDrillValues.push(ev.data._origin.dimension);
                config.filters.layerNum++;
                config.getChartByModuleId();
                config.partionDataShown = true;
                return false;
            });

            chart.render();
            return chart;
        },
        circularPie: function (data, config, $container, chartIdent) {
            this.mergeDimFieldNames(data, config);
            this.splitMeaFields(data, config);

            if (!config.filters.sortField) {
                data.sort(function (d1, d2) {
                    return d2.measure - d1.measure;
                });
            }

            var Stat = G2.Stat, chart = new G2.Chart({
                id: chartIdent,
                width: $container.width(),
                height: $container.height(),
                plotCfg: {
                    margin: [55, 90, 20, 20]
                }
            });
            chart.source(data);
            chart.coord('theta', {
                radius: 1,
                inner: 0.6
            });
            // chart.legend(false);
            chart.legend('dimension',{
                position:'right',
                title: null
            });

            chart.intervalStack().position(Stat.summary.percent('measure')).color('dimension', G2.Global.colors['default']).label('dimension*..percent', function (name, percent) {
                percent = (percent * 100).toFixed(2) + '%';
                return name + ' ' + percent;
            });

            // 下钻
            chart.on('plotclick', function (ev) {
                if (!config.isDrill || config.filters.layerNum == config.dimension.length - 1) {
                    return;
                }
                if (!ev.data) {
                    return;
                }
                config.downDrillValues.push(ev.data._origin.dimension);
                config.filters.layerNum++;
                config.getChartByModuleId();
                config.partionDataShown = true;
                return false;
            });

            chart.render();
            return chart;
        },
        nestedPie: function (data, config, $container, chartIdent) {
            var dimNames = this.translateDimensionFields(data, config);
            var meaNames = this.translateMeasureFields(data, config);

            var Stat = G2.Stat;
            var chart = new G2.Chart({
                id: chartIdent,
                width: $container.width(),
                height: $container.height(),
                plotCfg: {
                    margin: [75, 50, 50, 50]
                }
            });
            chart.source(data);
            chart.legend(false);
            chart.coord('theta', {
                radius: 0.5
            });
            chart.intervalStack().position(Stat.summary.percent(meaNames[0])).color(dimNames[0], G2.Global.colors['default']).label(dimNames[0], {
                offset: -20,
                label: {
                    fontSize: 14
                }
            });
            var view = chart.createView();
            view.source(data);
            view.coord('theta', {
                inner: 0.6
            });
            view.intervalStack().position(Stat.summary.percent(meaNames[0])).color(dimNames[1], G2.Global.colors['default']).label(dimNames[1] + '*' + dimNames[0]);
            chart.render();
            return chart;
        },
        line: function (data, config, $container, chartIdent) {
            // 整理维度字段
            this.mergeDimFieldNames(data, config);
            this.splitMeaFields(data, config);

            var dimLen = this.collectDimensionFieldKinds(data);
            var self = this;

            // 如果chart宽度太小则需要滚动
            if (dimLen * 10 > $container.width()) {
                $container.find('.echarts-container').width(dimLen * 10);
                $container.find('.echarts-container-scroll').mCustomScrollbar({
                    autoHideScrollbar: true,
                    theme: "inset-dark",
                    axis: 'x'
                });
            } else {
                $container.find('.echarts-container').width($container.width());
                $container.find('.echarts-container-scroll').mCustomScrollbar("disable", true);
            }

            var chart = new G2.Chart({
                id: chartIdent,
                width: $container.find('.echarts-container').width(),
                height: $container.height(),
                plotCfg: {
                    margin: [45, tools.mobileEnv() ? 20 : this.countMaxLegendLength(config, data) + 40, this.countAxisDistance($container, data), 80]
                }
            });

            // var colDefs = {};
            // colDefs['measure'] = {
            //     min: 0
            // };
            // angular.forEach(data, function (d) {
            //     d.dimension += ' ';
            // });
            var dimensions = [];
            for (var i = 0; i < data.length; i++) {
                if (dimensions.indexOf(data[i].dimension) == -1) {
                    dimensions.push(data[i].dimension);
                }
            }

            var colDefs = {};
            colDefs['measure'] = {
                min: 0
            };
            colDefs['dimension'] = {
                type: 'cat',
                values: dimensions
            }

            chart.source(data, colDefs);
            chart.axis('dimension', {
                title: null,
                labels: {
                    autoRotate: true
                }
            });
            chart.axis('measure', {
                title: null
            });
            chart.legend('dimension',{
                position:'right',
                title: null
            });
            // 单维度,多度量
            if (config.dimension.length == 1 && config.measure.length > 1) {
                chart.line().position('dimension*measure').color('name', G2.Global.colors['default']).shape('smooth').size(2);
            }

            // 单维度,单度量
            if (config.dimension.length == 1 && config.measure.length == 1) {
                if (!config.classifies.length) {
                    if(self.hasMeanLine(config)){
                        var frame = new G2.Frame(data);
                        var caratAvg = G2.Frame.mean(frame,'measure');
                        chart.guide().tag([data[0].dimension,caratAvg],[data[data.length-1].dimension,caratAvg],'平均值：'+caratAvg.toFixed(2));
                    }
                    chart.line().position('dimension*measure').color('name').shape('smooth').size(2);
                } else {
                    chart.line().position('dimension*measure').color('classification', G2.Global.colors['default']).shape('smooth').size(2);
                }
            }

            // 多维度,单度量
            if (config.dimension.length > 1 && config.measure.length == 1) {
                if (!config.classifies.length) {
                    chart.line().position('dimension*measure').shape('smooth').size(2);
                } else {
                    chart.line().position('dimension*measure').color('classification', G2.Global.colors['default']).shape('smooth').size(2);
                }
            }

            var selectContainer = $container.find('.selectContainer');
            var plotmovefn = function (ev) {
                if (config.selected || !config.keydownMode) {
                    return;
                }

                var point = {
                    x: ev.x,
                    y: ev.y
                };
                var items = chart.getTooltipItems(point);

                if (!config.startItem) {
                    config.startItem = items[0].title;
                    config.startPoint = point;
                    return;
                }

                config.endItem = items[0].title;
                config.endPoint = point;

                selectContainer.removeClass('none').css({
                    left: config.startPoint.x < config.endPoint.x ? config.startPoint.x - 5 : config.endPoint.x - 5,
                    top: config.startPoint.y < config.endPoint.y ? config.startPoint.y - 5 : config.endPoint.y - 5,
                    width: Math.abs(config.endPoint.x - config.startPoint.x),
                    height: Math.abs(config.endPoint.y - config.startPoint.y)
                });
            }
            chart.on('plotmove', plotmovefn);
            chart.legend({
                title: null
            });
            chart.render();
            return chart;
        },
        bar: function (data, config, $container, chartIdent) {
            var self = this;

            // 整理维度字段
            this.mergeDimFieldNames(data, config);
            this.splitMeaFields(data, config);
            var dimLen = this.collectDimensionFieldKinds(data);

            // 如果chart宽度太小则需要滚动
            if (dimLen * 15 > $container.width()) {
                $container.find('.echarts-container').width(dimLen * 20);
                $container.find('.echarts-container-scroll').mCustomScrollbar({
                    autoHideScrollbar: true,
                    theme: "inset-dark",
                    axis: 'x'
                });
            } else {
                $container.find('.echarts-container').width($container.width());
                $container.find('.echarts-container-scroll').mCustomScrollbar("destroy");
            }

            var Stat = G2.Stat;
            var chart = new G2.Chart({
                id: chartIdent,
                width: $container.find('.echarts-container').width(),
                height: $container.height(),
                plotCfg: {
                    // margin: [45, tools.mobileEnv() ? 20 : this.countMaxLegendLength(config, data) + 40, this.countAxisDistance($container, data)+20, 80]
                    margin: [45, tools.mobileEnv() ? 20 : this.countMaxLegendLength(config, data) + 40, 90, 80]
                }
            });


            angular.forEach(data, function (item) {
                item.measure_for_line = item.measure / 2;
            });

            var dimensions = [];
            for (var i = 0; i < data.length; i++) {
                if (dimensions.indexOf(data[i].dimension) == -1) {
                    dimensions.push(data[i].dimension);
                }
            }

            var colDefs = {};
            colDefs['measure'] = {
                // min: 0
            };
            colDefs['dimension'] = {
                type: 'cat',
                values: dimensions,

            };
            chart.source(data, colDefs);
            chart.axis('dimension', {
                title: null
            });
            chart.axis('measure', {
                title: null
            });

            if (tools.mobileEnv() || config.hasSecondY) {
                chart.legend(false);
            }
            chart.legend({
                title: null
            });
            // 单维度,单度量
            if (config.dimension.length == 1 && config.measure.length == 1) {
                if (!config.classifies.length) {
                        if(self.hasMeanLine(config)){
                            var frame = new G2.Frame(data);
                            var caratAvg = G2.Frame.mean(frame,'measure');
                            chart.guide().tag([data[0].dimension,caratAvg],[data[data.length-1].dimension,caratAvg],'平均值：'+caratAvg.toFixed(2));
                        }
                    
                    chart.interval().position(Stat.summary.mean('dimension*measure')).color('name', G2.Global.colors['default']);
                } else {
              //       if(self.hasMeanLine(config)){
                    //  var frame = new G2.Frame(data);
              //        var caratAvg = G2.Frame.mean(frame,'measure');
              //        chart.guide().tag([data[0].dimension,caratAvg],[data[data.length-1].dimension,caratAvg],'平均值：'+caratAvg.toFixed(2));
                    // }
                    chart.intervalStack().position(Stat.summary.mean('dimension*measure')).color('classification', G2.Global.colors['default']);
                }
            }

            // 单维度,多度量
            if (config.dimension.length == 1 && config.measure.length > 1) {
                if (!config.classifies.length) {
                    chart.intervalDodge().position('dimension*measure').color('name', G2.Global.colors['default']);

                    if (self.hasSecondY(config)) {
                        chart.axis('secondY' + secondYnames, {
                            title: null
                        });
                        var secondYnames = self.collectSecondYNames(config);

                        for (var i = 0; i < secondYnames.length; i++) {
                            chart.line().position('dimension*secondY' + secondYnames[i], ['#2f4554']).shape('smooth').size(2);
                            chart.point().position('dimension*secondY' + secondYnames[i]);
                        }
                    }
                } else {
                    // console.log(data)
                    if (self.hasSecondY(config)) {

                        var secondYnames = self.collectSecondYNames(config);
                        chart.axis('secondY' + secondYnames, {
                            title: null
                        });
                        chart.legend({
                            title: null,
                            position:'bottom'
                        });
                        chart.intervalStack().position('dimension*measure').color('classification', G2.Global.colors['default']);

                        for (var i = 0; i < secondYnames.length; i++) {
                            chart.line().position('dimension*secondY' + secondYnames[i], ['#2f4554']).color('classification').shape('smooth').size(2);
                            chart.point().position('dimension*secondY' + secondYnames[i]).color('classification');
                        }
                    }
                    //console.log(JSON.stringify(data));
                }
            }

            // 多维度,单度量
            if (config.dimension.length > 1 && config.measure.length == 1) {
                if (!config.classifies.length) {
                    
                    chart.interval().position(Stat.summary.mean('dimension*measure')).color('name', G2.Global.colors['default']);
                } else {
                    
                    chart.intervalStack().position(Stat.summary.mean('dimension*measure')).color('classification', G2.Global.colors['default']);
                }
            }

            // 多维度,多度量
            if (config.dimension.length > 1 && config.measure.length > 1) {
                
                chart.intervalDodge().position(Stat.summary.mean('dimension*measure')).color('name', G2.Global.colors['default']);
            }

            // 下钻
            chart.on('plotclick', function (ev) {
                if (!config.isDrill || config.filters.layerNum == config.dimension.length - 1) {
                    return;
                }
                config.downDrillValues.push(ev.data._origin.dimension);
                config.filters.layerNum++;
                config.getChartByModuleId();
                config.partionDataShown = true;
            });

            var selectContainer = $container.find('.selectContainer');
            var plotmovefn = function (ev) {
                if (config.selected || !config.keydownMode) {
                    return;
                }

                var point = {
                    x: ev.x,
                    y: ev.y
                };
                var items = chart.getTooltipItems(point);

                if (!config.startItem) {
                    config.startItem = items[0].title;
                    config.startPoint = point;
                    return;
                }

                config.endItem = items[0].title;
                config.endPoint = point;

                selectContainer.removeClass('none').css({
                    left: config.startPoint.x < config.endPoint.x ? config.startPoint.x - 5 : config.endPoint.x - 5,
                    top: config.startPoint.y < config.endPoint.y ? config.startPoint.y - 5 : config.endPoint.y - 5,
                    width: Math.abs(config.endPoint.x - config.startPoint.x),
                    height: Math.abs(config.endPoint.y - config.startPoint.y)
                });
            }
            chart.on('plotmove', plotmovefn);
            
            chart.render();
            return chart;
        },
        verBar: function (data, config, $container, chartIdent) {
            // 整理维度字段
            this.mergeDimFieldNames(data, config);
            this.splitMeaFields(data, config);

            var dimLen = this.collectDimensionFieldKinds(data);

            // 如果chart宽度太小则需要滚动
            if (dimLen * 10 > $container.height()) {
                $container.find('.echarts-container').height(dimLen * 20);
                $container.find('.echarts-container-scroll').mCustomScrollbar({
                    autoHideScrollbar: true,
                    theme: "inset-dark",
                    axis: 'y'
                });
            } else {
                $container.find('.echarts-container').height($container.height());
                $container.find('.echarts-container-scroll').mCustomScrollbar("disable", true);
            }

            function formatter (text, item) {
                return '<div class="">' + text + '</div>';
            }

            var Stat = G2.Stat;
            var chart = new G2.Chart({
                id: chartIdent,
                width: $container.width(),
                height: $container.find('.echarts-container').height(),
                plotCfg: {
                    margin: [45, tools.mobileEnv() ? 20 : this.countMaxLegendLength(config, data) + 40, 30, this.countAxisDistance($container, data) + 40]
                }
            });

            var colDefs = {};
            colDefs['measure'] = {
                min: 0
            };
            chart.source(data, colDefs);
            chart.axis('dimension', {
                title: null
            });
            chart.axis('measure', {
                title: null
            });
            chart.legend('bottom');

            chart.coord('rect').transpose(); // 旋转，缩放坐标轴

            // 单维度,单度量
            if (config.dimension.length == 1 && config.measure.length == 1) {
                if (!config.classifies.length) {
                    chart.interval().position(Stat.summary.mean('dimension*measure')).color('name', G2.Global.colors['default']);
                } else {
                    chart.intervalStack().position(Stat.summary.mean('dimension*measure')).color('classification', G2.Global.colors['default']);
                }
            }

            // 单维度,多度量
            if (config.dimension.length == 1 && config.measure.length > 1) {
                if (!config.classifies.length) {
                    chart.intervalDodge().position(Stat.summary.mean('dimension*measure')).color('name', G2.Global.colors['default']);
                } else {
                    // console.log(JSON.stringify(data));
                }
            }

            // 多维度,单度量
            if (config.dimension.length > 1 && config.measure.length == 1) {
                if (!config.classifies.length) {
                    chart.interval().position(Stat.summary.mean('dimension*measure')).color('name', G2.Global.colors['default']);
                } else {
                    chart.intervalStack().position(Stat.summary.mean('dimension*measure')).color('classification', G2.Global.colors['default']);
                }
            }

            // 多维度,多度量
            if (config.dimension.length > 1 && config.measure.length > 1) {
                chart.intervalDodge().position(Stat.summary.mean('dimension*measure')).color('name', G2.Global.colors['default']);
            }

            // 下钻
            chart.on('plotclick', function (ev) {
                if (!config.isDrill || config.filters.layerNum == config.dimension.length - 1) {
                    return;
                }
                config.downDrillValues.push(ev.data._origin.dimension);
                config.filters.layerNum++;
                config.getChartByModuleId();
                config.partionDataShown = true;
                ev.stopPropagation();
            });
            chart.legend({
                title: null
            });
            chart.render();
            return chart;
        },
        waterfall: function (data, config, $container, chartIdent) {
        },
        area: function (data, config, $container, chartIdent) {
            this.mergeDimFieldNames(data, config);
            this.translateMeasureFields(data, config);

            var Frame = G2.Frame;
            var frame = new Frame(data);
            frame = Frame.combinColumns(frame, this.collectMeausreTranslatedFieldNames(config), 'Revenue', 'City', 'dimension');
            var chart = new G2.Chart({
                id: chartIdent,
                width: $container.width(),
                height: $container.height(),
                plotCfg: {
                    margin: [45, tools.mobileEnv() ? 20 : this.countMaxLegendLength(config, data) + 40, this.countMaxLength(data) + 10, 80]
                }
            });
            chart.axis('dimension', {
                title: null
            });
            chart.axis('Revenue', {
                title: null
            });

            var dimensions = [];
            for (var i = 0; i < data.length; i++) {
                if (dimensions.indexOf(data[i].dimension) == -1) {
                    dimensions.push(data[i].dimension);
                }
            }

            var colDefs = {};
            colDefs['measure'] = {
                min: 0
            };
            colDefs['dimension'] = {
                type: 'cat',
                values: dimensions
            }

            chart.source(frame, colDefs);
            chart.areaStack().position('dimension*Revenue').color('City');
            chart.legend({
                title: null
            });
            chart.render();
            return chart;
        },
        bubble: function (data, config, $container, chartIdent) {
            this.translateDimensionFields(data, config);
            this.translateMeasureFields(data, config);
      
            var chart = new G2.Chart({
                id: chartIdent,
                width: $container.width(),
                height: $container.find('.echarts-container').height(),
                plotCfg: {
                    margin: [45, tools.mobileEnv() ? 20 : this.countMaxLegendLength(config, data) + 40, 100, 70]
                }
            });
            chart.source(data);
            chart.tooltip({
                title: null // 不显示默认标题
            });
            chart.legend(config.measure2[0].columnDesc, false);
            chart.legend(config.dimension[0].columnDesc,{
                position: 'bottom',
                title: null
            })
           
            chart.point().position(config.measure[0].columnDesc + '*' + config.measure[1].columnDesc).size(config.measure2[0].columnDesc, 35, 5).color(config.dimension[0].columnDesc).opacity(0.65).shape('circle').tooltip(config.dimension[0].columnDesc + '*' + config.measure[0].columnDesc + '*' + config.measure[1].columnDesc + '*' + config.measure2[0].columnDesc);
           
            chart.render();
            return chart;
        },
        scatter: function (data, config, $container, chartIdent) {
            var name = 'normal_' + config.dimension[0].fieldName;
            var dimension = 'normal_' + config.measure[0].fieldName;
            var measure = 'normal_' + config.measure[1].fieldName;
            var frame = new G2.Frame(data);
            var hAvg = G2.Frame.mean(frame, dimension);
            var wAvg = G2.Frame.mean(frame, measure);
            var lineCfg = { // 线的配置信息
                stroke: '#94E08A'
            };
            var chart = new G2.Chart({
                id: chartIdent,
                width: $container.width(),
                height: $container.height(),
                plotCfg: {
                    margin: [45, tools.mobileEnv() ? 20 : this.countMaxLegendLength(config, data) + 40, 60, 90]
                }
            });
            var colDefs = {};
            colDefs[dimension] = {
                alias: config.measure[0].columnDesc
            }
            colDefs[measure] = {
                alias: config.measure[1].columnDesc
            }
            
            chart.source(data,colDefs);
            chart.tooltip({
                title: null
            });
            chart.point().position(dimension + '*' + measure).color(name).shape('circle').tooltip(name + '*' + dimension + '*' + measure);
            chart.legend({
                title: null
            });
            chart.render();
            return chart;
        },
        radar: function (data, config, $container, chartIdent) {
            this.translateMeasureFields(data, config);

            G2.Global.axis.circle.grid = {
                line: {
                    stroke: '#d9d9d9',
                    'stroke-width': 1,
                    'stroke-dasharray': [0, 0]
                }
            };

            var measures = this.collectMeausreTranslatedFieldNames(config);
            var name = config.dimension[0].meaType + '_' + config.dimension[0].fieldName;

            var chart = new G2.Chart({
                id: chartIdent,
                width: $container.width(),
                height: $container.height(),
                plotCfg: {
                    margin: [55, tools.mobileEnv() ? 20 : this.countMaxLegendLength(config, data) + 60, 20, 30]
                }
            });
            var Frame = G2.Frame;
            var frame = new Frame(data);

            frame = Frame.combinColumns(frame, measures, 'value', 'categories', name);
            chart.source(frame, {
                'value': {
                    min: 0,
                    nice: false,
                    tickCount: 4
                }
            });
            chart.coord('polar');
            chart.legend('bottom');
            chart.axis('categories', { // 设置坐标系栅格样式
                line: null
            });
            chart.axis('value', {
                grid: {
                    type: 'polygon',
                    line: {
                        'stroke-dasharray': [0, 0]
                    }
                }
            });
            chart.line().position('categories*value').color(name);
            chart.point().position('categories*value').color(name).shape(name, ['rect', 'triangle']);
            chart.legend({
                title: null
            });
            chart.render();
            return chart;
        },
        funnel: function (data, config, $container, chartIdent) {
            var data_ = [];
            // for (var i in data[0]) {
            //     data_.push({
            //         action: i,
            //         value: data[0][i]
            //     });
            // }

            angular.forEach(config.measure, function (mea) {
                data_.push({
                    action: mea.columnDesc,
                    value: data[0][mea.meaType + '_' + mea.fieldName]
                });
            });

            var chart = new G2.Chart({
                id: chartIdent,
                width: $container.width(),
                height: $container.height(),
                plotCfg: {
                    margin: [50, 50]
                }
            });
            chart.source(data_);
            chart.coord('rect').transpose().scale(1, -1);
            chart.axis(false);
            chart.legend('action', {
                position: 'bottom',
                title: null
            });
            chart.intervalSymmetric().position('action*value').color('action', G2.Global.colors['default']).shape('funnel').label('action', {offset: 10, label: {fontSize: 14}});
            
            return chart.render();
        },
        histogram: function (data, config, $container, chartIdent) {
            var self = this;

            // 整理维度字段
            this.mergeDimFieldNames(data, config);
            this.splitMeaFields(data, config);
            var dimLen = this.collectDimensionFieldKinds(data);

            // 如果chart宽度太小则需要滚动
            if (dimLen * 15 > $container.width()) {
                $container.find('.echarts-container').width(dimLen * 20);
                $container.find('.echarts-container-scroll').mCustomScrollbar({
                    autoHideScrollbar: true,
                    theme: "inset-dark",
                    axis: 'x'
                });
            } else {
                $container.find('.echarts-container').width($container.width());
                $container.find('.echarts-container-scroll').mCustomScrollbar("destroy");
            }

            var Stat = G2.Stat;
            var chart = new G2.Chart({
                id: chartIdent,
                width: $container.find('.echarts-container').width(),
                height: $container.height(),
                plotCfg: {
                    // margin: [45, tools.mobileEnv() ? 20 : this.countMaxLegendLength(config, data) + 40, this.countAxisDistance($container, data)+20, 80]
                    margin: [45, tools.mobileEnv() ? 20 : this.countMaxLegendLength(config, data) + 40, 90, 80]
                }
            });


            angular.forEach(data, function (item) {
                item.measure_for_line = item.measure / 2;
            });

            var dimensions = [];
            for (var i = 0; i < data.length; i++) {
                if (dimensions.indexOf(data[i].dimension) == -1) {
                    dimensions.push(data[i].dimension);
                }
            }

            var colDefs = {};
            colDefs['measure'] = {
                // min: 0
            };
            colDefs['dimension'] = {
                type: 'cat',
                values: dimensions,

            };
            chart.source(data, colDefs);
            chart.axis('dimension', {
                title: null
            });
            chart.axis('measure', {
                title: null
            });
            chart.legend('top right');

            if (tools.mobileEnv()) {
                chart.legend(false);
            }
            // 单维度,单度量
            if (config.dimension.length == 1 && config.measure.length == 1) {
                if (!config.classifies.length) {
                        if(self.hasMeanLine(config)){
                            var frame = new G2.Frame(data);
                            var caratAvg = G2.Frame.mean(frame,'measure');
                            chart.guide().tag([data[0].dimension,caratAvg],[data[data.length-1].dimension,caratAvg],'平均值：'+caratAvg.toFixed(2));
                        }
                    
                    chart.interval().position(Stat.summary.mean('dimension*measure')).color('name', G2.Global.colors['default']);
                } else {
                   
                   
                    chart.intervalStack().position(Stat.summary.mean('dimension*measure')).color('classification', G2.Global.colors['default']);
                }
            }

            // 下钻
            chart.on('plotclick', function (ev) {
                if (!config.isDrill || config.filters.layerNum == config.dimension.length - 1) {
                    return;
                }
                config.downDrillValues.push(ev.data._origin.dimension);
                config.filters.layerNum++;
                config.getChartByModuleId();
                config.partionDataShown = true;
            });

            var selectContainer = $container.find('.selectContainer');
            var plotmovefn = function (ev) {
                if (config.selected || !config.keydownMode) {
                    return;
                }

                var point = {
                    x: ev.x,
                    y: ev.y
                };
                var items = chart.getTooltipItems(point);

                if (!config.startItem) {
                    config.startItem = items[0].title;
                    config.startPoint = point;
                    return;
                }

                config.endItem = items[0].title;
                config.endPoint = point;

                selectContainer.removeClass('none').css({
                    left: config.startPoint.x < config.endPoint.x ? config.startPoint.x - 5 : config.endPoint.x - 5,
                    top: config.startPoint.y < config.endPoint.y ? config.startPoint.y - 5 : config.endPoint.y - 5,
                    width: Math.abs(config.endPoint.x - config.startPoint.x),
                    height: Math.abs(config.endPoint.y - config.startPoint.y)
                });
            }
            chart.on('plotmove', plotmovefn);
            chart.legend({
                title: null
            });
            chart.render();
            return chart;
        },
        treemap: function (data, config, $container, chartIdent) {
            var self = this;

            // 整理维度字段
            this.mergeDimFieldNames(data, config);
            this.splitMeaFields(data, config);

            try {
                var Stat = G2.Stat;
                var chart = new G2.Chart({
                    id: chartIdent,
                    width: $container.width(),
                    height: $container.height(),
                    plotCfg: {
                        margin: [45, 10, config.isDrill && config.layerNum > 0 ? 30 : 10, 10]
                    }
                });
            } catch (e) {
                if (tools.mobileEnv()) {
                    // alert(G2);
                    alert(e.message);
                }
            }

            chart.source(data);
            chart.axis(false);
            chart.legend(false);

            chart.polygon().position(Stat.treemap('1*' + 'measure')).color('dimension').shape('stroke').label('dimension', {
                label: {
                    fontWeight: 'bold'
                }
            });

            // 下钻
            chart.on('plotclick', function (ev) {
                if (!config.isDrill || config.filters.layerNum == config.dimension.length - 1) {
                    return;
                }
                config.downDrillValues.push(ev.data._origin.dimension);
                config.filters.layerNum++;
                config.getChartByModuleId();
                config.partionDataShown = true;
                ev.stopPropagation();
            });
            chart.render();
            return chart;
        },
        dashboard: function (data, config, $container, chartIdent) {
        },
        provinceMap: function (data, config, $container, chartIdent) {
            this.mergeDimFieldNames(data, config);
            this.splitMeaFields(data, config);

            data_ = [];

            var totalProvs = ['甘肃', '青海', '广西', '贵州', '重庆', '北京', '福建', '安徽', '广东', '西藏', '新疆',
                '海南', '宁夏', '陕西', '山西', '湖北', '湖南', '四川', '云南', '河北', '河南', '辽宁', '山东', '天津',
                '江西', '江苏', '上海', '浙江', '吉林', '内蒙古', '黑龙江', '台湾', '南海诸岛', '香港', '澳门'];

            for (var i = 0; i < totalProvs.length; i++) {
                data_.push({
                    dimension: totalProvs[i],
                    measure: 0
                });
            }

            data_ = data_.concat(data);

            // 清理省份的名字
            for (var i = 0; i < data_.length; i++) {
                for (var j = 0; j < totalProvs.length; j++) {
                    if (data_[i].dimension.indexOf(totalProvs[j]) != -1) {
                        data_[i].dimension = totalProvs[j];
                    }
                }
            }

            var Stat = G2.Stat;
            var chart = new G2.Chart({
                id: chartIdent,
                width: $container.width(),
                height: $container.height(),
                plotCfg: {
                    margin: [30, 80]
                }
            });
            chart.source(data_);
            chart.axis(false);
            chart.polygon().position(Stat.map.region('dimension', mapData)).color('measure', '#dddddd-#2f4554').style({
                stroke: '#333',
                lineWidth: 1
            });
            chart.point().position(Stat.map.center('dimension', mapData)).color('name').label('dimension', {
                offset: 0,
                label: {
                    fill: '#000',
                    fontSize: 10
                }
            }).size(0);
            chart.render();
            return chart;
        },
        cityMap: function (data, config, $container, chartIdent) {
            this.mergeDimFieldNames(data, config);
            this.splitMeaFields(data, config);

            var data_ = [];

            for (var i = 0; i < data.length; i++) {
                for (var c in chinaCitys) {
                    if (data[i].dimension.indexOf(c) != -1 || c.indexOf(data[i].dimension) != -1) {
                        data[i].lant = chinaCitys[c].lant;
                        data[i].long = chinaCitys[c].long;
                        data_.push(data[i]);
                        break;
                    }
                }
            }

            var Frame = G2.Frame;
            var Stat = G2.Stat;

            var map = [];
            var features = worldGeoMap.features;
            for (var i = 0; i < features.length; i++) {
                var name = features[i].properties.name;
                map.push({
                    "name": name
                });
            }

            var chart = new G2.Chart({
                id: chartIdent,
                width: $container.width(),
                height: $container.height(),
                plotCfg: {
                    margin: [30, 30]
                }
            });
            chart.legend(false);
            chart.tooltip({
                title: null
            });
            var bgView = chart.createView();
            bgView.source(map);
            bgView.tooltip(false);
            bgView.coord('map', {
                projection: 'albers',
                basic: [110, 0, 25, 47],
                max: [16.573, -13.613],
                min: [-27.187, -49.739] // 指定投影后最小的坐标点
            });
            bgView.axis(false);
            bgView.polygon().position(Stat.map.region('name', worldGeoMap)).color('name', function (val) {
                if (val === 'China') {
                    return '#C7C7C7';
                } else {
                    return '#ffffff';
                }
            }).style({
                stroke: '#fff',
                lineWidth: 3
            });

            var pointView = chart.createView({
                index: 1
            });
            pointView.source(data_, {
                dimension: {
                    alias: config.dimension[0].columnDesc
                },
                measure: {
                    alias: config.measure[0].columnDesc
                }
            });
            pointView.coord('map', {
                projection: 'albers',
                basic: [110, 0, 25, 47],
                max: [16.573, -13.613],
                min: [-27.187, -49.739]
            });
            pointView.point().position(Stat.map.location('long*lant')).size('measure', 12, 1).color('#2f4554').tooltip('dimension*measure').shape('circle').style({
                shadowBlur: 10,
                shadowColor: '#6A006F'
            });
            chart.render();
            return chart;
        },
        heatmap: function (data, config, $container, chartIdent) {
            this.mergeMapFieldNames(data,config)
            var self = this;
            // document.getElementById(chartIdent).width($container.width()).height($container.height())
            $('#'+chartIdent).width($container.width()).height($container.height())
            $('#'+chartIdent).css('z-index','-1!important')
            var map = new BMap.Map(chartIdent);          // 创建地图实例

            var point = new BMap.Point(116.418261, 39.921984);
            map.centerAndZoom(point, 15);             // 初始化地图，设置中心点坐标和地图级别
            map.enableScrollWheelZoom(); // 允许滚轮缩放
            // map.disableDragging();
            var menu = new BMap.ContextMenu();
            var txtMenuItem = [
                {
                    name: '删除',
                    icon: 'trash icon',
                    callback:function(){
                        if (config.moduleId) {
                            $rootScope.$broadcast('CONFIRM_EV', {
                                title: '图删除提醒',
                                content: '图表删除之后不可恢复,确定删除吗?',
                                btns: {
                                    yes: {
                                        text: "确定删除",
                                        fn: function () {
                                            self.deleteIbmModuleChartByModuleId(config)
                                            //chartServ.deleteIbmModuleChartByModuleId(config);
                                        }
                                    },
                                    no: {
                                        text: '取消',
                                        fn: function () {

                                        }
                                    }
                                }
                            });
                        } else {
                            $rootScope.delChart(config.tmpId);
                            // 清空字段
                            $rootScope.$broadcast('FIELD_RECOVER_FROM_CHART_EV', [], [],[],[],[], config.chartType,'');
                            $rootScope.$broadcast('CONTEXTMENU_OFF_EV');
                            $rootScope.$broadcast('CONFIRM_OFF_EV');
                        }
                    }
                    
                }
            ];
            for(var i=0; i < txtMenuItem.length; i++){

                menu.addItem(new BMap.MenuItem(txtMenuItem[i].name,txtMenuItem[i].callback,0));
            }
            map.addContextMenu(menu);

            // var data =[
            //     {"lng":116.418261,"lat":39.921984,"count":50},
            //     {"lng":116.423332,"lat":39.916532,"count":51},
            //     {"lng":116.419787,"lat":39.930658,"count":15},
            //     {"lng":116.418455,"lat":39.920921,"count":40},
            //     {"lng":116.418843,"lat":39.915516,"count":100},
            //     {"lng":116.42546,"lat":39.918503,"count":6},
            //     {"lng":116.423289,"lat":39.919989,"count":18},
            //     {"lng":116.418162,"lat":39.915051,"count":80},
            //     {"lng":116.422039,"lat":39.91782,"count":11},
            //     {"lng":116.41387,"lat":39.917253,"count":7},
            //     {"lng":116.41773,"lat":39.919426,"count":42},
            //     {"lng":116.421107,"lat":39.916445,"count":4},
            //     {"lng":116.417521,"lat":39.917943,"count":27},
            //     {"lng":116.419812,"lat":39.920836,"count":23},
            //     {"lng":116.420682,"lat":39.91463,"count":60},
            //     {"lng":116.415424,"lat":39.924675,"count":8},
            //     {"lng":116.419242,"lat":39.914509,"count":15},
            //     {"lng":116.422766,"lat":39.921408,"count":25},
            //     {"lng":116.421674,"lat":39.924396,"count":21},
            //     {"lng":116.427268,"lat":39.92267,"count":1},
            //     {"lng":116.417721,"lat":39.920034,"count":51},
            //     {"lng":116.412456,"lat":39.92667,"count":7},
            //     {"lng":116.420432,"lat":39.919114,"count":11},
            //     {"lng":116.425013,"lat":39.921611,"count":35},
            //     {"lng":116.418733,"lat":39.931037,"count":22},
            //     {"lng":116.419336,"lat":39.931134,"count":4},
            //     {"lng":116.413557,"lat":39.923254,"count":5},
            //     {"lng":116.418367,"lat":39.92943,"count":3},
            //     {"lng":116.424312,"lat":39.919621,"count":100},
            //     {"lng":116.423874,"lat":39.919447,"count":87},
            //     {"lng":116.424225,"lat":39.923091,"count":32},
            //     {"lng":116.417801,"lat":39.921854,"count":44},
            //     {"lng":116.417129,"lat":39.928227,"count":21},
            //     {"lng":116.426426,"lat":39.922286,"count":80},
            //     {"lng":116.421597,"lat":39.91948,"count":32},
            //     {"lng":116.423895,"lat":39.920787,"count":26},
            //     {"lng":116.423563,"lat":39.921197,"count":17},
            //     {"lng":116.417982,"lat":39.922547,"count":17},
            //     {"lng":116.426126,"lat":39.921938,"count":25},
            //     {"lng":116.42326,"lat":39.915782,"count":100},
            //     {"lng":116.419239,"lat":39.916759,"count":39},
            //     {"lng":116.417185,"lat":39.929123,"count":11},
            //     {"lng":116.417237,"lat":39.927518,"count":9},
            //     {"lng":116.417784,"lat":39.915754,"count":47},
            //     {"lng":116.420193,"lat":39.917061,"count":52},
            //     {"lng":116.422735,"lat":39.915619,"count":100},
            //     {"lng":116.418495,"lat":39.915958,"count":46},
            //     {"lng":116.416292,"lat":39.931166,"count":9},
            //     {"lng":116.419916,"lat":39.924055,"count":8},
            //     {"lng":116.42189,"lat":39.921308,"count":11},
            //     {"lng":116.413765,"lat":39.929376,"count":3},
            //     {"lng":116.418232,"lat":39.920348,"count":50},
            //     {"lng":116.417554,"lat":39.930511,"count":15},
            //     {"lng":116.418568,"lat":39.918161,"count":23},
            //     {"lng":116.413461,"lat":39.926306,"count":3},
            //     {"lng":116.42232,"lat":39.92161,"count":13},
            //     {"lng":116.4174,"lat":39.928616,"count":6},
            //     {"lng":116.424679,"lat":39.915499,"count":21},
            //     {"lng":116.42171,"lat":39.915738,"count":29},
            //     {"lng":116.417836,"lat":39.916998,"count":99},
            //     {"lng":116.420755,"lat":39.928001,"count":10},
            //     {"lng":116.414077,"lat":39.930655,"count":14},
            //     {"lng":116.426092,"lat":39.922995,"count":16},
            //     {"lng":116.41535,"lat":39.931054,"count":15},
            //     {"lng":116.413022,"lat":39.921895,"count":13},
            //     {"lng":116.415551,"lat":39.913373,"count":17},
            //     {"lng":116.421191,"lat":39.926572,"count":1},
            //     {"lng":116.419612,"lat":39.917119,"count":9},
            //     {"lng":116.418237,"lat":39.921337,"count":54},
            //     {"lng":116.423776,"lat":39.921919,"count":26},
            //     {"lng":116.417694,"lat":39.92536,"count":17},
            //     {"lng":116.415377,"lat":39.914137,"count":19},
            //     {"lng":116.417434,"lat":39.914394,"count":43},
            //     {"lng":116.42588,"lat":39.922622,"count":27},
            //     {"lng":116.418345,"lat":39.919467,"count":8},
            //     {"lng":116.426883,"lat":39.917171,"count":3},
            //     {"lng":116.423877,"lat":39.916659,"count":34},
            //     {"lng":116.415712,"lat":39.915613,"count":14},
            //     {"lng":116.419869,"lat":39.931416,"count":12},
            //     {"lng":116.416956,"lat":39.925377,"count":11},
            //     {"lng":116.42066,"lat":39.925017,"count":38},
            //     {"lng":116.416244,"lat":39.920215,"count":91},
            //     {"lng":116.41929,"lat":39.915908,"count":54},
            //     {"lng":116.422116,"lat":39.919658,"count":21},
            //     {"lng":116.4183,"lat":39.925015,"count":15},
            //     {"lng":116.421969,"lat":39.913527,"count":3},
            //     {"lng":116.422936,"lat":39.921854,"count":24},
            //     {"lng":116.41905,"lat":39.929217,"count":12},
            //     {"lng":116.424579,"lat":39.914987,"count":57},
            //     {"lng":116.42076,"lat":39.915251,"count":70},
            //     {"lng":116.425867,"lat":39.918989,"count":8}
            // ];
            if(!isSupportCanvas()){
                alert('热力图目前只支持有canvas支持的浏览器,您所使用的浏览器不能使用热力图功能~')
            }
            heatmapOverlay = new BMapLib.HeatmapOverlay({"radius":20});
            map.addOverlay(heatmapOverlay);
            heatmapOverlay.setDataSet({data:data,max:100});
            function setGradient(){
                var gradient = {};
                var colors = document.querySelectorAll("input[type='color']");
                colors = [].slice.call(colors,0);
                colors.forEach(function(ele){
                    gradient[ele.getAttribute("data-key")] = ele.value; 
                });
                heatmapOverlay.setOptions({"gradient":gradient});
            };
            function isSupportCanvas(){
                var elem = document.createElement('canvas');
                return !!(elem.getContext && elem.getContext('2d'));
            }

           return map;

        },
        heatmarketmap: function (data, config, $container, chartIdent) {
            this.mergeMapFieldNames(data,config)
            var self = this;
            // document.getElementById(chartIdent).width($container.width()).height($container.height())
            $('#'+chartIdent).width($container.width()).height($container.height())
            $('#'+chartIdent).css('z-index','-1!important')
            var map = new BMap.Map(chartIdent);          // 创建地图实例

            var point = new BMap.Point(116.418261, 39.921984);
            map.centerAndZoom(point, 15);             // 初始化地图，设置中心点坐标和地图级别
            map.enableScrollWheelZoom(); // 允许滚轮缩放
            // map.disableDragging();
            var menu = new BMap.ContextMenu();
            var txtMenuItem = [
                {
                    name: '删除',
                    icon: 'trash icon',
                    callback:function(){
                        if (config.moduleId) {
                            $rootScope.$broadcast('CONFIRM_EV', {
                                title: '图删除提醒',
                                content: '图表删除之后不可恢复,确定删除吗?',
                                btns: {
                                    yes: {
                                        text: "确定删除",
                                        fn: function () {
                                            self.deleteIbmModuleChartByModuleId(config)
                                            //chartServ.deleteIbmModuleChartByModuleId(config);
                                        }
                                    },
                                    no: {
                                        text: '取消',
                                        fn: function () {

                                        }
                                    }
                                }
                            });
                        } else {
                            $rootScope.delChart(config.tmpId);
                            // 清空字段
                            $rootScope.$broadcast('FIELD_RECOVER_FROM_CHART_EV', [], [],[],[],[], config.chartType,'');
                            $rootScope.$broadcast('CONTEXTMENU_OFF_EV');
                            $rootScope.$broadcast('CONFIRM_OFF_EV');
                        }
                    }
                    
                }
            ];
            for(var i=0; i < txtMenuItem.length; i++){

                menu.addItem(new BMap.MenuItem(txtMenuItem[i].name,txtMenuItem[i].callback,0));
            }
            map.addContextMenu(menu);

            // var data =[
            //     {"lng":116.418261,"lat":39.921984,"count":50},
            //     {"lng":116.423332,"lat":39.916532,"count":51},
            //     {"lng":116.419787,"lat":39.930658,"count":15},
            //     {"lng":116.418455,"lat":39.920921,"count":40},
            //     {"lng":116.418843,"lat":39.915516,"count":100},
            //     {"lng":116.42546,"lat":39.918503,"count":6},
            //     {"lng":116.423289,"lat":39.919989,"count":18},
            //     {"lng":116.418162,"lat":39.915051,"count":80},
            //     {"lng":116.422039,"lat":39.91782,"count":11},
            //     {"lng":116.41387,"lat":39.917253,"count":7},
            //     {"lng":116.41773,"lat":39.919426,"count":42},
            //     {"lng":116.421107,"lat":39.916445,"count":4},
            //     {"lng":116.417521,"lat":39.917943,"count":27},
            //     {"lng":116.419812,"lat":39.920836,"count":23},
            //     {"lng":116.420682,"lat":39.91463,"count":60},
            //     {"lng":116.415424,"lat":39.924675,"count":8},
            //     {"lng":116.419242,"lat":39.914509,"count":15},
            //     {"lng":116.422766,"lat":39.921408,"count":25},
            //     {"lng":116.421674,"lat":39.924396,"count":21},
            //     {"lng":116.427268,"lat":39.92267,"count":1},
            //     {"lng":116.417721,"lat":39.920034,"count":51},
            //     {"lng":116.412456,"lat":39.92667,"count":7},
            //     {"lng":116.420432,"lat":39.919114,"count":11},
            //     {"lng":116.425013,"lat":39.921611,"count":35},
            //     {"lng":116.418733,"lat":39.931037,"count":22},
            //     {"lng":116.419336,"lat":39.931134,"count":4},
            //     {"lng":116.413557,"lat":39.923254,"count":5},
            //     {"lng":116.418367,"lat":39.92943,"count":3},
            //     {"lng":116.424312,"lat":39.919621,"count":100},
            //     {"lng":116.423874,"lat":39.919447,"count":87},
            //     {"lng":116.424225,"lat":39.923091,"count":32},
            //     {"lng":116.417801,"lat":39.921854,"count":44},
            //     {"lng":116.417129,"lat":39.928227,"count":21},
            //     {"lng":116.426426,"lat":39.922286,"count":80},
            //     {"lng":116.421597,"lat":39.91948,"count":32},
            //     {"lng":116.423895,"lat":39.920787,"count":26},
            //     {"lng":116.423563,"lat":39.921197,"count":17},
            //     {"lng":116.417982,"lat":39.922547,"count":17},
            //     {"lng":116.426126,"lat":39.921938,"count":25},
            //     {"lng":116.42326,"lat":39.915782,"count":100},
            //     {"lng":116.419239,"lat":39.916759,"count":39},
            //     {"lng":116.417185,"lat":39.929123,"count":11},
            //     {"lng":116.417237,"lat":39.927518,"count":9},
            //     {"lng":116.417784,"lat":39.915754,"count":47},
            //     {"lng":116.420193,"lat":39.917061,"count":52},
            //     {"lng":116.422735,"lat":39.915619,"count":100},
            //     {"lng":116.418495,"lat":39.915958,"count":46},
            //     {"lng":116.416292,"lat":39.931166,"count":9},
            //     {"lng":116.419916,"lat":39.924055,"count":8},
            //     {"lng":116.42189,"lat":39.921308,"count":11},
            //     {"lng":116.413765,"lat":39.929376,"count":3},
            //     {"lng":116.418232,"lat":39.920348,"count":50},
            //     {"lng":116.417554,"lat":39.930511,"count":15},
            //     {"lng":116.418568,"lat":39.918161,"count":23},
            //     {"lng":116.413461,"lat":39.926306,"count":3},
            //     {"lng":116.42232,"lat":39.92161,"count":13},
            //     {"lng":116.4174,"lat":39.928616,"count":6},
            //     {"lng":116.424679,"lat":39.915499,"count":21},
            //     {"lng":116.42171,"lat":39.915738,"count":29},
            //     {"lng":116.417836,"lat":39.916998,"count":99},
            //     {"lng":116.420755,"lat":39.928001,"count":10},
            //     {"lng":116.414077,"lat":39.930655,"count":14},
            //     {"lng":116.426092,"lat":39.922995,"count":16},
            //     {"lng":116.41535,"lat":39.931054,"count":15},
            //     {"lng":116.413022,"lat":39.921895,"count":13},
            //     {"lng":116.415551,"lat":39.913373,"count":17},
            //     {"lng":116.421191,"lat":39.926572,"count":1},
            //     {"lng":116.419612,"lat":39.917119,"count":9},
            //     {"lng":116.418237,"lat":39.921337,"count":54},
            //     {"lng":116.423776,"lat":39.921919,"count":26},
            //     {"lng":116.417694,"lat":39.92536,"count":17},
            //     {"lng":116.415377,"lat":39.914137,"count":19},
            //     {"lng":116.417434,"lat":39.914394,"count":43},
            //     {"lng":116.42588,"lat":39.922622,"count":27},
            //     {"lng":116.418345,"lat":39.919467,"count":8},
            //     {"lng":116.426883,"lat":39.917171,"count":3},
            //     {"lng":116.423877,"lat":39.916659,"count":34},
            //     {"lng":116.415712,"lat":39.915613,"count":14},
            //     {"lng":116.419869,"lat":39.931416,"count":12},
            //     {"lng":116.416956,"lat":39.925377,"count":11},
            //     {"lng":116.42066,"lat":39.925017,"count":38},
            //     {"lng":116.416244,"lat":39.920215,"count":91},
            //     {"lng":116.41929,"lat":39.915908,"count":54},
            //     {"lng":116.422116,"lat":39.919658,"count":21},
            //     {"lng":116.4183,"lat":39.925015,"count":15},
            //     {"lng":116.421969,"lat":39.913527,"count":3},
            //     {"lng":116.422936,"lat":39.921854,"count":24},
            //     {"lng":116.41905,"lat":39.929217,"count":12},
            //     {"lng":116.424579,"lat":39.914987,"count":57},
            //     {"lng":116.42076,"lat":39.915251,"count":70},
            //     {"lng":116.425867,"lat":39.918989,"count":8}
            // ];
            if(!isSupportCanvas()){
                alert('热力图目前只支持有canvas支持的浏览器,您所使用的浏览器不能使用热力图功能~')
            }

            var MAX = 10;
            var markers = [];
            var pt = null;
   
            for (var i = 0; i < data.length; i++) {
               pt = new BMap.Point(data[i].lng, data[i].lat);
               markers.push(new BMap.Marker(pt));
            }
            //最简单的用法，生成一个marker数组，然后调用markerClusterer类即可。
            var markerClusterer = new BMapLib.MarkerClusterer(map, {markers:markers});
            function isSupportCanvas(){
                var elem = document.createElement('canvas');
                return !!(elem.getContext && elem.getContext('2d'));
            }

           return map;

        },

    }
}]);